<?php
class JSMin
{
    const ORD_LF = 10;
    const ORD_SPACE = 32;
    protected $a = '';
    protected $b = '';
    protected $input = '';
    protected $inputIndex = 0;
    protected $inputLength = 0;
    protected $lookAhead = null;
    protected $output = '';
    // -- Public Static Methods --------------------------------------------------
    public static function minify ($js)
    {
        $jsmin = new JSMin($js);
        return $jsmin->min();
    }
    // -- Public Instance Methods ------------------------------------------------
    public function __construct ($input)
    {
        $this->input = str_replace("\r\n", "\n", $input);
        $this->inputLength = strlen($this->input);
    }
    // -- Protected Instance Methods ---------------------------------------------
    protected function action ($d)
    {
        switch ($d) {
            case 1:
                $this->output .= $this->a;
            case 2:
                $this->a = $this->b;
                if ($this->a === "'" || $this->a === '"') {
                    for (;;) {
                        $this->output .= $this->a;
                        $this->a = $this->get();
                        if ($this->a === $this->b) {
                            break;
                        }
                        if (ord($this->a) <= self::ORD_LF) {
                            throw new JSMinException('Unterminated string literal.');
                        }
                        if ($this->a === '\\') {
                            $this->output .= $this->a;
                            $this->a = $this->get();
                        }
                    }
                }
            case 3:
                $this->b = $this->next();
                if ($this->b === '/' && ($this->a === '(' || $this->a === ',' || $this->a === '=' || $this->a === ':' || $this->a === '[' || $this->a === '!' || $this->a === '&' || $this->a === '|' || $this->a === '?')) {
                    $this->output .= $this->a . $this->b;
                    for (;;) {
                        $this->a = $this->get();
                        if ($this->a === '/') {
                            break;
                        } elseif ($this->a === '\\') {
                            $this->output .= $this->a;
                            $this->a = $this->get();
                        } elseif (ord($this->a) <= self::ORD_LF) {
                            throw new JSMinException('Unterminated regular expression ' . 'literal.');
                        }
                        $this->output .= $this->a;
                    }
                    $this->b = $this->next();
                }
        }
    }
    protected function get ()
    {
        $c = $this->lookAhead;
        $this->lookAhead = null;
        if ($c === null) {
            if ($this->inputIndex < $this->inputLength) {
                $c = substr($this->input, $this->inputIndex, 1);
                $this->inputIndex += 1;
            } else {
                $c = null;
            }
        }
        if ($c === "\r") {
            return "\n";
        }
        if ($c === null || $c === "\n" || ord($c) >= self::ORD_SPACE) {
            return $c;
        }
        return ' ';
    }
    protected function isAlphaNum ($c)
    {
        return ord($c) > 126 || $c === '\\' || preg_match('/^[\w\$]$/', $c) === 1;
    }
    protected function min ()
    {
        $this->a = "\n";
        $this->action(3);
        while ($this->a !== null) {
            switch ($this->a) {
                case ' ':
                    if ($this->isAlphaNum($this->b)) {
                        $this->action(1);
                    } else {
                        $this->action(2);
                    }
                    break;
                case "\n":
                    switch ($this->b) {
                        case '{':
                        case '[':
                        case '(':
                        case '+':
                        case '-':
                            $this->action(1);
                            break;
                        case ' ':
                            $this->action(3);
                            break;
                        default:
                            if ($this->isAlphaNum($this->b)) {
                                $this->action(1);
                            } else {
                                $this->action(2);
                            }
                    }
                    break;
                default:
                    switch ($this->b) {
                        case ' ':
                            if ($this->isAlphaNum($this->a)) {
                                $this->action(1);
                                break;
                            }
                            $this->action(3);
                            break;
                        case "\n":
                            switch ($this->a) {
                                case '}':
                                case ']':
                                case ')':
                                case '+':
                                case '-':
                                case '"':
                                case "'":
                                    $this->action(1);
                                    break;
                                default:
                                    if ($this->isAlphaNum($this->a)) {
                                        $this->action(1);
                                    } else {
                                        $this->action(3);
                                    }
                            }
                            break;
                        default:
                            $this->action(1);
                            break;
                    }
            }
        }
        return $this->output;
    }
    protected function next ()
    {
        $c = $this->get();
        if ($c === '/') {
            switch ($this->peek()) {
                case '/':
                    for (;;) {
                        $c = $this->get();
                        if (ord($c) <= self::ORD_LF) {
                            return $c;
                        }
                    }
                case '*':
                    $this->get();
                    for (;;) {
                        switch ($this->get()) {
                            case '*':
                                if ($this->peek() === '/') {
                                    $this->get();
                                    return ' ';
                                }
                                break;
                            case null:
                                throw new JSMinException('Unterminated comment.');
                        }
                    }
                default:
                    return $c;
            }
        }
        return $c;
    }
    protected function peek ()
    {
        $this->lookAhead = $this->get();
        return $this->lookAhead;
    }
}
/**
 * Класс отвечающий за минимизацию и слияние скриптов
 * @author Chashin Evgeniy
 * @version 1.1
 */
class Zen_Script
{
    /**
     * Возвращает текущий контэйнер для скриптоав
     * @return array
     */
    static function getContainer ()
    {
        if (Zend_Registry::isRegistered('scripts')) {
            $styles = Zend_Registry::get('scripts');
        } else
            $styles = array();
        return $styles;
    }
    /**
     * Сохраняет текущие скрипты
     * @param array $scripts
     */
    static function setContainer ($scripts)
    {
        Zend_Registry::set('scripts', $scripts);
    }
    /**
     * Добавление файла для загрузки
     * @param string $name - относительный путь до js файла
     * @param int $order - порядок загрузки 
     * @param string $library - имя библиотеки (файлы с одинаковым именем библиотеки подгружаються одним файлом)
     */
    static function add ($name, $library = 0, $order = 0, $exclude = false)
    {
        
        $scripts = self::getContainer();
        if (! isset($scripts['files'][$name])) {
            while (isset($scripts['libs'][$library][$order])) {
                $order ++;
            }
            $scripts['libs'][$library][$order] = array('name' => $name , 'order' => $order , 'lib' => $library, 'exclude' => $exclude);
            $scripts['files'][$name] = array('name' => $name , 'order' => $order , 'lib' => $library, 'exclude' => $exclude);
        }
        self::setContainer($scripts);
    }
    /**
     * Удаление файла из списка
     * @param strng $name - относительный путь до js файла
     */
    static function remove ($name)
    {
        $scripts = self::getContainer();
        if (isset($scripts['files'][$name])) {
            $file = $scripts['files'][$name];
            unset($scripts['libs'][$file['lib']][$file['order']]);
            unset($scripts['files'][$name]);
        }
        self::setContainer($scripts);
    }
    /**
     * вывод скриптов
     * @return string
     */
    static function render ()
    {
        
        if (Zend_Registry::isRegistered('scripts')) {
            $scripts = Zend_Registry::get('scripts');
       
            $res = "";
            if (sizeof($scripts) > 0) {
                //Сортировка
                foreach ($scripts['libs'] as $lib => $value) {
                    ksort($scripts['libs'][$lib]);
                }
                ksort($scripts['libs']);
                
                
                $cnf = Zend_Registry::get('cnf');
                
            
    		if (! file_exists ( $cnf->cache_dir.'jscss')) {
				mkdir ( $cnf->cache_dir.'jscss', 0777, true );
			}
                
                
                if ($cnf->scripts->implode == false) {
                    foreach ($scripts['libs'] as $lib => $files) {
                    	foreach ($files as $script) {
                        	$res .= '
                        	<script type="text/javascript" src="' . $script['name'] . '"></script>'.PHP_EOL;
                    	}
                    }
                } else {
                    foreach ($scripts['libs'] as $lib => $files) {
                        $cache_file_name = "";
                        $data = "";
                        foreach ($files as $key=>$file) {
                        	if(!preg_match('/^http/', $file['name']) && !$file['exclude']){
                           		$file['name']=preg_replace('/^\//','',trim($file['name']));
                           		$root=preg_replace('/\\/$/','',ROOT_PATH);
                            	$name=preg_replace('/^\\//','',$file['name']);
                            	$real_name = $root .'/'. $name;
                            	try {
	                                $date=false;
    	                            $date = filemtime($real_name);
                                	if($date==false)
                                	{
                                    	throw new Exception("Cant,t read file '".$real_name."'");
                                	}
                                	else{
                                    	$cache_file_name .= $file['name'] . $date;        
                                	}
	                            } catch (Exception $e) {
	                                echo $e->getMessage();
	                            }
                        	}else{
                        		$res .= '
                        		<script type="text/javascript" src="' . $file['name'] . '"></script>'.PHP_EOL;
                        		unset($files[$key]);
                        	}
                        }
                        
                        $cache_file_name = md5($lib . $cache_file_name);
                        $rel_path = '/site/cache/jscss/' . $cache_file_name . ".js";
                        if (! file_exists($cnf->cache_dir . 'jscss/' . $cache_file_name . ".js")) {
                            if(sizeof($files)>0){
                        	foreach ($files as $file) {
                                $name=preg_replace('/^\//','',trim($file['name']));
                                $root=preg_replace('/\\/$/','',ROOT_PATH);
                                $real_name = $root .'/'. $name;
                                $content=file_get_contents($real_name);
                                $path = explode('/', $file['name']);
                                $c = sizeof($path) - 1;
                                $fname = $path[$c];
                                $path = str_replace($fname, '', $file);
                                $data .= JSMin::minify($content);
                            }
                            }
                         	file_put_contents($cnf->cache_dir . 'jscss/' . $cache_file_name . ".js", $data);   
                        }
                        $res .= '
                         <script type="text/javascript" src="'.$rel_path .'"></script>';
                    }
                }
                return $res;
            }
        }
    }
}